"use client"

import { useState, useEffect } from "react"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Move, Palette, TypeIcon, ImageIcon } from "lucide-react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import type { Layer } from "@/components/image-analyzer"

interface LayerEditorProps {
  layer: Layer
  onLayerUpdate: (layer: Layer) => void
}

export default function LayerEditor({ layer, onLayerUpdate }: LayerEditorProps) {
  const [editedContent, setEditedContent] = useState(layer.content)

  const [fontSize, setFontSize] = useState(layer.style?.fontSize || "16px")
  const [fontFamily, setFontFamily] = useState(layer.style?.fontFamily || "sans-serif")
  const [fontWeight, setFontWeight] = useState(layer.style?.fontWeight || "400")
  const [fontStyle, setFontStyle] = useState(layer.style?.fontStyle || "normal")
  const [textAlign, setTextAlign] = useState(layer.style?.textAlign || "left")
  const [lineHeight, setLineHeight] = useState(layer.style?.lineHeight || "")
  const [letterSpacing, setLetterSpacing] = useState(layer.style?.letterSpacing || "")
  const [color, setColor] = useState(layer.style?.color || "#000000")
  const [backgroundColor, setBackgroundColor] = useState(layer.style?.backgroundColor || "")
  const [borderRadius, setBorderRadius] = useState(layer.style?.borderRadius || "")
  const [opacity, setOpacity] = useState(layer.style?.opacity || "1")

  // Position state
  const [posX, setPosX] = useState(layer.position?.x || 0)
  const [posY, setPosY] = useState(layer.position?.y || 0)
  const [width, setWidth] = useState(layer.position?.width || 100)
  const [height, setHeight] = useState(layer.position?.height || 50)

  // Image-specific style states
  const [filter, setFilter] = useState(layer.style?.filter || "")
  const [brightness, setBrightness] = useState("100")
  const [contrast, setContrast] = useState("100")
  const [saturation, setSaturation] = useState("100")
  const [blur, setBlur] = useState("0")

  useEffect(() => {
    setEditedContent(layer.content)
    setFontSize(layer.style?.fontSize || "16px")
    setFontFamily(layer.style?.fontFamily || "sans-serif")
    setFontWeight(layer.style?.fontWeight || "400")
    setFontStyle(layer.style?.fontStyle || "normal")
    setTextAlign(layer.style?.textAlign || "left")
    setLineHeight(layer.style?.lineHeight || "")
    setLetterSpacing(layer.style?.letterSpacing || "")
    setColor(layer.style?.color || "#000000")
    setBackgroundColor(layer.style?.backgroundColor || "")
    setBorderRadius(layer.style?.borderRadius || "")
    setOpacity(layer.style?.opacity || "1")

    setFilter(layer.style?.filter || "")

    // Parse existing filter values
    const filterStr = layer.style?.filter || ""
    const brightnessMatch = filterStr.match(/brightness$$(\d+)%?$$/)
    const contrastMatch = filterStr.match(/contrast$$(\d+)%?$$/)
    const saturationMatch = filterStr.match(/saturate$$(\d+)%?$$/)
    const blurMatch = filterStr.match(/blur$$(\d+)px$$/)

    setBrightness(brightnessMatch ? brightnessMatch[1] : "100")
    setContrast(contrastMatch ? contrastMatch[1] : "100")
    setSaturation(saturationMatch ? saturationMatch[1] : "100")
    setBlur(blurMatch ? blurMatch[1] : "0")
  }, [layer])

  useEffect(() => {
    const timer = setTimeout(() => {
      handleSave()
    }, 300)
    return () => clearTimeout(timer)
  }, [
    editedContent,
    fontSize,
    fontFamily,
    fontWeight,
    fontStyle,
    textAlign,
    lineHeight,
    letterSpacing,
    color,
    backgroundColor,
    borderRadius,
    opacity,
    brightness,
    contrast,
    saturation,
    blur,
  ])

  const handleSave = () => {
    const filterParts = []
    if (brightness !== "100") filterParts.push(`brightness(${brightness}%)`)
    if (contrast !== "100") filterParts.push(`contrast(${contrast}%)`)
    if (saturation !== "100") filterParts.push(`saturate(${saturation}%)`)
    if (blur !== "0") filterParts.push(`blur(${blur}px)`)
    const filterString = filterParts.length > 0 ? filterParts.join(" ") : undefined

    const updatedLayer: Layer = {
      ...layer,
      content: editedContent,
      position: {
        x: posX,
        y: posY,
        width,
        height,
      },
      style: {
        ...layer.style,
        fontSize,
        fontFamily,
        fontWeight,
        fontStyle,
        textAlign,
        lineHeight: lineHeight || undefined,
        letterSpacing: letterSpacing || undefined,
        color,
        backgroundColor: backgroundColor || undefined,
        borderRadius: borderRadius || undefined,
        opacity,
        filter: filterString,
      },
    }
    onLayerUpdate(updatedLayer)
  }

  return (
    <ScrollArea className="h-[500px] pr-4">
      <div className="space-y-4">
        <div>
          <h3 className="text-sm font-semibold mb-1 text-foreground">Edit {layer.type} Layer</h3>
          <p className="text-xs text-muted-foreground">
            Drag layer on canvas to move, use handle to resize, or edit properties below
          </p>
        </div>

        <div className="space-y-4">
          {/* Content */}
          <div className="space-y-2">
            <Label htmlFor="content" className="text-sm font-medium text-foreground">
              Content
            </Label>
            {layer.type === "text" ? (
              <Textarea
                id="content"
                value={editedContent}
                onChange={(e) => setEditedContent(e.target.value)}
                className="min-h-[80px] bg-background"
                placeholder="Enter text content..."
              />
            ) : (
              <Input
                id="content"
                value={editedContent}
                onChange={(e) => setEditedContent(e.target.value)}
                className="bg-background"
                placeholder="Layer description..."
              />
            )}
          </div>

          <Separator />

          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Move className="h-4 w-4 text-primary" />
              <Label className="text-sm font-medium text-foreground">Position & Size</Label>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <div>
                <Label htmlFor="posX" className="text-xs text-muted-foreground">
                  X Position (px)
                </Label>
                <Input
                  id="posX"
                  type="number"
                  value={posX}
                  onChange={(e) => setPosX(Number(e.target.value))}
                  className="bg-background"
                />
              </div>
              <div>
                <Label htmlFor="posY" className="text-xs text-muted-foreground">
                  Y Position (px)
                </Label>
                <Input
                  id="posY"
                  type="number"
                  value={posY}
                  onChange={(e) => setPosY(Number(e.target.value))}
                  className="bg-background"
                />
              </div>
              <div>
                <Label htmlFor="width" className="text-xs text-muted-foreground">
                  Width (px)
                </Label>
                <Input
                  id="width"
                  type="number"
                  value={width}
                  onChange={(e) => setWidth(Number(e.target.value))}
                  className="bg-background"
                />
              </div>
              <div>
                <Label htmlFor="height" className="text-xs text-muted-foreground">
                  Height (px)
                </Label>
                <Input
                  id="height"
                  type="number"
                  value={height}
                  onChange={(e) => setHeight(Number(e.target.value))}
                  className="bg-background"
                />
              </div>
            </div>
          </div>

          {layer.type === "text" && (
            <>
              <Separator />
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <TypeIcon className="h-4 w-4 text-primary" />
                  <Label className="text-sm font-medium text-foreground">Typography</Label>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="fontFamily" className="text-xs text-muted-foreground">
                    Font Family
                  </Label>
                  <Select value={fontFamily} onValueChange={setFontFamily}>
                    <SelectTrigger className="bg-background">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="sans-serif">Sans Serif</SelectItem>
                      <SelectItem value="serif">Serif</SelectItem>
                      <SelectItem value="monospace">Monospace</SelectItem>
                      <SelectItem value="Arial, sans-serif">Arial</SelectItem>
                      <SelectItem value="Helvetica, sans-serif">Helvetica</SelectItem>
                      <SelectItem value="'Times New Roman', serif">Times New Roman</SelectItem>
                      <SelectItem value="Georgia, serif">Georgia</SelectItem>
                      <SelectItem value="'Courier New', monospace">Courier New</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-2">
                    <Label htmlFor="fontSize" className="text-xs text-muted-foreground">
                      Font Size
                    </Label>
                    <Input
                      id="fontSize"
                      value={fontSize}
                      onChange={(e) => setFontSize(e.target.value)}
                      className="bg-background"
                      placeholder="16px"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="fontWeight" className="text-xs text-muted-foreground">
                      Font Weight
                    </Label>
                    <Select value={fontWeight} onValueChange={setFontWeight}>
                      <SelectTrigger className="bg-background">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="300">Light</SelectItem>
                        <SelectItem value="400">Normal</SelectItem>
                        <SelectItem value="500">Medium</SelectItem>
                        <SelectItem value="600">Semi Bold</SelectItem>
                        <SelectItem value="700">Bold</SelectItem>
                        <SelectItem value="900">Black</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-2">
                    <Label htmlFor="fontStyle" className="text-xs text-muted-foreground">
                      Font Style
                    </Label>
                    <Select value={fontStyle} onValueChange={setFontStyle}>
                      <SelectTrigger className="bg-background">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="normal">Normal</SelectItem>
                        <SelectItem value="italic">Italic</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="textAlign" className="text-xs text-muted-foreground">
                      Text Align
                    </Label>
                    <Select value={textAlign} onValueChange={setTextAlign}>
                      <SelectTrigger className="bg-background">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="left">Left</SelectItem>
                        <SelectItem value="center">Center</SelectItem>
                        <SelectItem value="right">Right</SelectItem>
                        <SelectItem value="justify">Justify</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-2">
                    <Label htmlFor="lineHeight" className="text-xs text-muted-foreground">
                      Line Height
                    </Label>
                    <Input
                      id="lineHeight"
                      value={lineHeight}
                      onChange={(e) => setLineHeight(e.target.value)}
                      className="bg-background"
                      placeholder="1.5"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="letterSpacing" className="text-xs text-muted-foreground">
                      Letter Spacing
                    </Label>
                    <Input
                      id="letterSpacing"
                      value={letterSpacing}
                      onChange={(e) => setLetterSpacing(e.target.value)}
                      className="bg-background"
                      placeholder="0px"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="color" className="text-xs text-muted-foreground">
                    Text Color
                  </Label>
                  <div className="flex gap-2">
                    <Input
                      id="color"
                      type="color"
                      value={color}
                      onChange={(e) => setColor(e.target.value)}
                      className="w-16 h-10 p-1 bg-background cursor-pointer"
                    />
                    <Input
                      value={color}
                      onChange={(e) => setColor(e.target.value)}
                      className="flex-1 bg-background font-mono text-xs"
                      placeholder="#000000"
                    />
                  </div>
                </div>
              </div>
            </>
          )}

          {layer.type === "image" && (
            <>
              <Separator />
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <ImageIcon className="h-4 w-4 text-primary" />
                  <Label className="text-sm font-medium text-foreground">Image Adjustments</Label>
                </div>

                <div className="space-y-3">
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label htmlFor="brightness" className="text-xs text-muted-foreground">
                        Brightness
                      </Label>
                      <span className="text-xs text-muted-foreground">{brightness}%</span>
                    </div>
                    <Input
                      id="brightness"
                      type="range"
                      min="0"
                      max="200"
                      value={brightness}
                      onChange={(e) => setBrightness(e.target.value)}
                      className="bg-background"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label htmlFor="contrast" className="text-xs text-muted-foreground">
                        Contrast
                      </Label>
                      <span className="text-xs text-muted-foreground">{contrast}%</span>
                    </div>
                    <Input
                      id="contrast"
                      type="range"
                      min="0"
                      max="200"
                      value={contrast}
                      onChange={(e) => setContrast(e.target.value)}
                      className="bg-background"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label htmlFor="saturation" className="text-xs text-muted-foreground">
                        Saturation
                      </Label>
                      <span className="text-xs text-muted-foreground">{saturation}%</span>
                    </div>
                    <Input
                      id="saturation"
                      type="range"
                      min="0"
                      max="200"
                      value={saturation}
                      onChange={(e) => setSaturation(e.target.value)}
                      className="bg-background"
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label htmlFor="blur" className="text-xs text-muted-foreground">
                        Blur
                      </Label>
                      <span className="text-xs text-muted-foreground">{blur}px</span>
                    </div>
                    <Input
                      id="blur"
                      type="range"
                      min="0"
                      max="20"
                      value={blur}
                      onChange={(e) => setBlur(e.target.value)}
                      className="bg-background"
                    />
                  </div>
                </div>
              </div>
            </>
          )}

          <Separator />
          <div className="space-y-3">
            <div className="flex items-center gap-2">
              <Palette className="h-4 w-4 text-primary" />
              <Label className="text-sm font-medium text-foreground">Styling</Label>
            </div>

            <div className="space-y-2">
              <Label htmlFor="backgroundColor" className="text-xs text-muted-foreground">
                Background Color
              </Label>
              <div className="flex gap-2">
                <Input
                  id="backgroundColor"
                  type="color"
                  value={backgroundColor || "#ffffff"}
                  onChange={(e) => setBackgroundColor(e.target.value)}
                  className="w-16 h-10 p-1 bg-background cursor-pointer"
                />
                <Input
                  value={backgroundColor}
                  onChange={(e) => setBackgroundColor(e.target.value)}
                  className="flex-1 bg-background font-mono text-xs"
                  placeholder="transparent"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-2">
              <div className="space-y-2">
                <Label htmlFor="borderRadius" className="text-xs text-muted-foreground">
                  Border Radius
                </Label>
                <Input
                  id="borderRadius"
                  value={borderRadius}
                  onChange={(e) => setBorderRadius(e.target.value)}
                  className="bg-background"
                  placeholder="0px"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="opacity" className="text-xs text-muted-foreground">
                  Opacity
                </Label>
                <Input
                  id="opacity"
                  type="number"
                  min="0"
                  max="1"
                  step="0.1"
                  value={opacity}
                  onChange={(e) => setOpacity(e.target.value)}
                  className="bg-background"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </ScrollArea>
  )
}
